package com.sunchp.nio.sample.reactor;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class Acceptor implements Handler {
    private Selector selector;
    private ThreadPoolHandler threadPoolHandler;

    public Acceptor(Selector selector, ThreadPoolHandler threadPoolHandler) {
        this.selector = selector;
        this.threadPoolHandler = threadPoolHandler;
    }

    @Override
    public void handle(SelectionKey key) {
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();

        try {
            SocketChannel socketChannel = serverSocketChannel.accept();
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ, threadPoolHandler);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
